<!-- wang editor富文本编辑器 -->
<template>
  <div style="border: 1px solid #ccc">
    <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig" :mode="mode" />
    <Editor
      v-model="valueHtml"
      style="height: 300px; overflow-y: hidden"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="handleCreated"
      @onChange="handleChange"
    />
  </div>
</template>
<script setup>
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import { onBeforeUnmount, ref, shallowRef, onMounted, nextTick, watch } from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
// 初始值
const props = defineProps({
  index: Number,
  initValue: String,
  father_method: Function
});
const emits = defineEmits(["getEditorContent"]);
const mode = ref("default");
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();
// 内容 HTML
const valueHtml = ref("");
onMounted(() => {
  nextTick(() => {
    // 界面节点更新完以后再修改值。
    valueHtml.value = props.initValue;
  });
});
// 工具栏配置
const toolbarConfig = {};
const editorConfig = {
  placeholder: "请输入内容..."
};
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});
const handleCreated = editor => {
  editorRef.value = editor;
};
const handleChange = info => {
  // info.children 数组包含了数据类型和内容，valueHtml.value内容的html格式
  // console.log("变化后", info.children);
  if (info.children[0].type == "paragraph") {
    // emits("getEditorContent", info.children[0].text, valueHtml.value);
    emits("getEditorContent", info.children[0].text, valueHtml.value);
  }
};
const getContent = () => {
  // emits("getEditorContent", editorRef.value.getHtml(), editorRef.value.getText());
  return {
    htmlVal: editorRef.value.getHtml(),
    textVal: editorRef.value.getText()
  };
};

const setContent = html => {
  editorRef.value.setHtml(html);
};
watch(
  () => props.initValue,
  value => {
    // 父组件获取初始值
    // valueHtml.value = value
  }
);
defineExpose({
  valueHtml,
  getContent,
  setContent
});
</script>
